package com.itxx.homeWork.demo2;

import com.itxx.homeWork.domain.Student;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class ReflectionTest {
    //通过反射成员方法调用方法
    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        //创建Class对象
        Class aClass = Class.forName("com.itxx.homeWork.domain.Student");
        //创建Constructor   无参构造方法对象
        Constructor constructor = aClass.getDeclaredConstructor();

        Constructor constructor1 = aClass.getDeclaredConstructor(String.class, Integer.class);

        //无参创建Stu对象
        Student stu1 = (Student) constructor.newInstance();
        Field name = aClass.getDeclaredField("name");
        name.setAccessible(true);
        name.set(stu1, "李四");
        Field age = aClass.getDeclaredField("age");
        age.setAccessible(true);
        age.set(stu1, 34);
        System.out.println(stu1);

        System.out.println("------");
        //有参创建Stu对象
        Student stu2 = (Student) constructor1.newInstance("张三", 12);
        System.out.println(stu2);
        System.out.println("------");

        Method study = aClass.getDeclaredMethod("study");
        study.setAccessible(true);
        study.invoke(stu1);
        study.invoke(stu2);




    }

}
